﻿using Microsoft.Owin.Hosting;
using Seagull.BarTender.Print;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LabelPrint
{
    public partial class NewUpLabel : Form
    {
        string DefaultPrinter1;
        public NewUpLabel()
        {
            InitializeComponent();
        }
        LabelFormatDocument btFormat;
        private Engine engine = null; // The BarTender Print Engine
        private void NewUpLabel_Load(object sender, EventArgs e)
        {
           
            try
            {
                engine = new Engine(true);
            }
            catch (PrintEngineException exception)
            {
                // If the engine is unable to start, a PrintEngineException will be thrown.
                MessageBox.Show(this, exception.Message);
                this.Close(); // Close this app. We cannot run without connection to an engine.
                return;
            }
            // 得到打印机列表
            Printers printers = new Printers();
            foreach (Printer printer in printers)
            {
                cboPrinters.Items.Add(printer.PrinterName);
            }

            // cboPrinters.SelectedItem = btFormat.PrintSetup.PrinterName;
            cboPrinters.SelectedItem = DefaultPrinter();
            DefaultPrinter1 = DefaultPrinter();
            
        }

        private static PrintDocument fPrintDocument = new PrintDocument();
        //获取本机默认打印机名称
        public static String DefaultPrinter()
        {
            return fPrintDocument.PrinterSettings.PrinterName;
        }
        string aa="";
        string bb="";
        string cc="";
        string dd="";
        string ff="";
        string ee = "";
        string gg = "";
        string hh = "";
        string ii = "";
        string spec = "";
        string time = "";
        private void button1_Click(object sender, EventArgs e)
        {
            SQLServerDataBase sql = new SQLServerDataBase();

            if (oldCode.Text==""|| print_sl_txt.Text=="")
            {
                MessageBox.Show("工单和数量不能为空");
                return;
            }
            DataSet ds = new DataSet();
            string sqlString = "SELECT A.UDF021, B.ITEM_SPECIFICATION,PLAN_QTY,B.ITEM_CODE,C.LOT_CODE FROM MO A LEFT JOIN ITEM B ON A.ITEM_ID = B.ITEM_BUSINESS_ID LEFT JOIN ITEM_LOT C ON A.ITEM_LOT_ID = C.ITEM_LOT_ID WHERE DOC_NO = '" + oldCode.Text + "' ";
             sql.ExecuteNonDataSet(sqlString, out ds);

            DataTable table = ds.Tables[0];
              time = table.Rows[0][0].ToString();//time250304
           aa =  changeString(time);
            aa = aa.Substring(2);
             bb = table.Rows[0][1].ToString();//功率
            
            string[] bbarr = bb.Split(' ');
            bb = bbarr[2];
            spec = bbarr[0];

            cc = getQty(spec)+"PCS";
             dd = table.Rows[0][3].ToString();//品名
             ee = table.Rows[0][4].ToString();//批次号
            printBtw("newSbq.txt", "newSbq");
        }

        private string changeString(string str)
        {

         
            StringBuilder sb = new StringBuilder(str);
            sb.Replace("0", "A", 3, 1);
            sb.Replace("1", "B", 3, 1);
            sb.Replace("2", "C", 3, 1);
            sb.Replace("3", "D", 3, 1);
            sb.Replace("4", "E", 3, 1);
            sb.Replace("5", "F", 3, 1);
            sb.Replace("6", "G", 3, 1);
            sb.Replace("7", "H", 3, 1);
            sb.Replace("8", "I", 3, 1);
            sb.Replace("9", "J", 3, 1);
            str = sb.ToString();


            return str;
        }

        private string getQty(string spec)
        {
            // 0402 每卷是50K，每盒是250K，0603 / 0805 / 1206每卷是20K，每盒是100K
            string qty = "";
            switch (spec)
            {
                case "0201":
              
                    
                        qty = "15000";
                    
                 
                    break;

                case "0402":
             
                   
                        qty = "10000";
                    
                   
                    break;

                case "0603":
  
                        qty = "5000";
                  
                    break;

                case "0805":
       
                        qty = "5000";
                 
                    break;

                case "1206":
    
                        qty = "5000";

                    break;
                case "1210":
                 
                        qty = "5000";
                   
               
                    break;



                case "2010":
     
                        qty = "4000";
                 
                    break;

                case "2512":
                        qty = "4000";
                    
                    break;
                default:
                    break;
            }
            return qty;
        }

      public void printBtw(string FieldPath, string btw_path)
        {
            lock (engine)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory;
                string serialNumber = "time|wattage|quantity|item_name|lot_no|u_int|addr|customer_name\r\n" + aa + "|" + bb + "|" + cc.ToString() + "|" + dd + "|" + ee + "|" + time + "|" + gg + "|" + hh + "|" + ii;
                using (StreamWriter stream = new StreamWriter(path + "\\" + FieldPath))
                {
                    stream.Write(serialNumber);
                }
                //Lable 路径 

                string filePath = path + btw_path + ".btw";
                btFormat = engine.Documents.Open(filePath);
                //如何传参 命名具名数据源 赋予对应的 key<>value
                //          btFormat.SubStrings["ProductName"].Value = “test1”;
                //传入打印机名称
                btFormat.PrintSetup.PrinterName = DefaultPrinter();
                //打印张数
                btFormat.PrintSetup.IdenticalCopiesOfLabel =Convert.ToInt32(print_sl_txt.Text);
                //     MessageBox.Show("开始打印");

                Messages messages;
                string appName = "下标打印任务";
                Result result = btFormat.Print(appName, 10000, out messages);
                string messageString = "\n\nMessages:";

                foreach (Seagull.BarTender.Print.Message message in messages)
                {
                    messageString += "\n\n" + message.Text;
                }

                if (result == Result.Failure)
                    MessageBox.Show(this, "Print Failed" + messageString, appName);
                else
                    MessageBox.Show(this, "文本已成功发送到打印机" + messageString, appName);
            }

            //btFormat.Close(SaveOptions.DoNotSaveChanges);
            //    engine.Stop();
            //}



        }
        private bool isClosing = false; // 如果我们正在关闭，请设置为true。这有助于停止加载缩略图。
        private void NewUpLabel_FormClosed(object sender, FormClosedEventArgs e)
        {
            isClosing = true;

            // Make sure the thumbnail worker is stopped before we try closing BarTender or 
            // there might be problems in the worker.
            //thumbnailCacheWorker.CancelAsync();
            //while (thumbnailCacheWorker.IsBusy)
            //{
            //    Application.DoEvents();
            //};

            // Quit the BarTender Print Engine, but do not save changes to any open formats.
            if (engine != null)
                engine.Stop(SaveOptions.DoNotSaveChanges);
        }
        private IDisposable _disposable;
        private void ShutDownWebApi()
        {
            if (_disposable != null)
            {
                _disposable.Dispose();
                _disposable = null;
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                //端口号
                string port = "9000";
                //电脑所有ip地址都启用该端口服务
                //  string baseAddress = "http://localhost:" + port + "/";
                ////指定ip地址启用该端口服务
                string baseAddress = "http://192.168.2.99:" + port + "/";
                //启动OWIN host 
                using (WebApp.Start<Startup>(url: baseAddress))
                {
                    // Create HttpClient and make a request to api/values 
                    HttpClient client = new HttpClient();

                    var response = client.GetAsync(baseAddress + "api/print/test").Result;

                    Console.WriteLine(response);
                   MessageBox.Show(response.Content.ReadAsStringAsync().Result);
               //     Console.ReadLine();
                }
                //打印服务所用端口号
                MessageBox.Show("Http服务端口：" + port);
                //测试结果
                //创建HttpCient测试webapi 

            }
            catch (Exception ex)
            {
                MessageBox.Show("Http服务初始化失败！");
                MessageBox.Show(ex.ToString());
              //  Console.ReadLine();
            }
        }

        private void NewUpLabel_FormClosing(object sender, FormClosingEventArgs e)
        {
            ShutDownWebApi();
    
        
    }
    }
}
